package liuh.com.ledlamp.util;

import android.content.Context;
import android.util.Log;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InvalidClassException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * @author :liuh
 * @note
 * @date: 2016-12-05
 */

public class FileKit {
    private final static String tag = FileKit.class.getSimpleName();

    private Context mContext;

    public FileKit(Context mContext) {
        super();
        this.mContext = mContext;
    }

    /**
     * 保存对象
     * @param ser
     * @param fileName
     * @throws IOException
     */
    public boolean saveObject(Object ser, String fileName) throws IOException {
        String file = fileName + ".dat";
        FileOutputStream fos = null;
        ObjectOutputStream oos = null;
        try {
            fos = mContext.openFileOutput(file, Context.MODE_PRIVATE);
            oos = new ObjectOutputStream(fos);
            oos.writeObject(ser);
            oos.flush();
            return true;
        } catch (Exception e) {
            Log.e(tag, e.getMessage());
            throw e;
        } finally {
            try {
                oos.close();
                fos.close();
            } catch (Exception e) {
                throw e;
            }
        }
    }

    /**
     * 读取对象
     * @param fileName
     * @return
     * @throws IOException
     */
    public Object readObject(String fileName) throws Exception{
        String file = fileName + ".dat";
        if (!isExistDataCache(file))
            return null;
        FileInputStream fis = null;
        ObjectInputStream ois = null;
        try {
            fis = mContext.openFileInput(file);
            ois = new ObjectInputStream(fis);
            return (Object) ois.readObject();
        } catch (Exception e) {
            Log.e(tag, e.getMessage());
            // 反序列化失败 - 删除缓存文件
            if (e instanceof InvalidClassException) {
                File data = mContext.getFileStreamPath(file);
                data.delete();
            }
            throw e;
        } finally {
            try {
                ois.close();
                fis.close();
            } catch (Exception e) {
                throw e;
            }
        }
    }

    /**

     * 判断缓存是否存在

     *

     * @param cachefile

     * @return

     */
    private boolean isExistDataCache(String cachefile) {
        boolean exist = false;
        File data = mContext.getFileStreamPath(cachefile);
        if (data.exists()) {
            exist = true;
        }
        return exist;
    }
}
